<template>
    <div class="workorder">
        <div class="page-main">
            <div class="main-left">
                <el-form :model="formData" ref="leftForm" :rules="formDataRules" label-width="100px" label-position="left" size="mini" :hide-required-asterisk="false" :disabled="globalState" class="demo-ruleForm">
                    <el-form-item label="报工方式" prop="reportWay">
                        <el-radio-group v-model="formData.reportWay">
                            <el-radio :label="0">装配报工</el-radio>
                            <el-radio :label="1">EPC报工</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="线体" prop="lineName">
                        <el-select v-model="formData.lineName" placeholder="下拉选择线体" size="small">
                            <el-option v-for="(item,index) in lineNameList" :label="item" :value="item" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="品名" prop="materialCode">
                        <el-select v-model="formData.materialCode" placeholder="下拉选择产品" size="small">
                            <el-option v-for="(item,index) in materialList" :label="item.materialCode" :value="item.materialCode" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="订单" prop="productOrder">
                        <el-select v-model="formData.productOrder" placeholder="下拉选择订单" size="small">
                            <el-option v-for="item,index in formData.productOrderList" :label="item.productOrderMaterial.productOrderNumber" :value="item.productOrderMaterial.productOrderNumber" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="班次" prop="classes">
                        <el-select v-model="formData.classes" placeholder="下拉选择班次" size="mini">
                            <el-option v-for="item,index in formData.classesList" :label="item.shiftType" :value="item.shiftType" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="停机信息">
                        <el-form size="mini">
                            <el-form-item>
                                <el-button plain type="primary"  @click="wirteDowntReason">{{ globalState ? "点击查看" : downtReasonBtnInfo }}</el-button>
                                <downt-reason :disabled="true" ref="downtReason" :downtReasonDisabled="globalState" :reasonDataList="formData.downtReasonList" @close="downtReasonClose"></downt-reason>
                            </el-form-item>
                        </el-form>
                    </el-form-item>
                </el-form>
            </div>
            <div class="main-right">
                <el-form :model="formData" ref="rightForm" :rules="formDataRules" label-width="100px" label-position="left" size="mini" :disabled="globalState" :hide-required-asterisk="false" class="demo-ruleForm">
                    <el-form-item label="完成数量" prop="finishedNum">
                        <el-input v-model="formData.finishedNum" @input="formData.finishedNum = String(formData.finishedNum).replace(/[^\d]/g, '')" size="small" placeholder="请输入完成数量"></el-input>
                    </el-form-item>
                    <el-form-item label="不合格数" prop="unQualifiedNum" size="small" :disabled="globalState">
                        <el-input v-model="formData.unQualifiedNum" @input="formData.unQualifiedNum = String(formData.unQualifiedNum).replace(/[^\d]/g, '')" size="small" placeholder="请输入不合格数量"></el-input>
                    </el-form-item>
                    <el-form-item label="计划数量" size="small" :disabled="globalState">
                        <el-input v-model="formData.planNumber" placeholder="自动读取" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="合格数量" size="small">
                        <el-input :value="qualifiedNum"  placeholder="自动计算" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="设备运行时长" prop="equipmentRunningHours" size="small">
                        <el-input v-model="formData.equipmentRunningHours" @input="formData.equipmentRunningHours = String(formData.equipmentRunningHours).replace(/[^0-9.]|(\.\d{2,})|\D(?=\.)|^\./g, '')" placeholder="请输入设备运行时长(H)"></el-input>
                    </el-form-item>
                    <el-form-item label="出勤工时" prop="attendanceHours" size="small">
                        <el-input v-model="formData.attendanceHours" @input="formData.attendanceHours = String(formData.attendanceHours).replace(/[^0-9.]|(\.\d{2,})|\D(?=\.)|^\./g, '')" placeholder="请输入出勤工时"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="page-records">
            <template v-if="formData.reportWay !== 1">
                <div class="records-head">
                    <div class="head-title">报废记录</div>
                    <div class="head-main">
                        <div class="main-item">
                            <span class="item-tip">日期:</span>
                            <el-date-picker v-model="records.date" type="date" :editable="false" value-format="yyyy-MM-dd" size="mini" placeholder="请选择时间" :disabled="globalState"></el-date-picker>
                        </div>
                        <div class="main-item">
                            <span class="item-tip">作业员:</span>
                            <span class="item-tip item-content">{{ nickname }}</span>
                        </div>
                    </div>
                </div>
                <div class="records-process">
                    <div class="process-content">
                        <div class="process-table">
                            <el-table :data="records.recordTable" border style="width:100%" size="small" max-height="200">
                                <el-table-column prop="processName" label="工序" width=""></el-table-column>
                                <el-table-column prop="defectQuantity" label="不良数量" width="">
                                    <template slot-scope="{ row, $index }">
                                        <el-input v-model.number="row.defectQuantity" size="small" @input="processInputEvent($event,row,$index)" style="width:60%;" :disabled="globalState" placeholder="请输入不良数量"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div class="bom-table">
                            <el-table :data="records.processMaterialTable" border style="width:100%" size="small" max-height="200">
                                <el-table-column prop="materialName" label="工序用料" width=""></el-table-column>
                                <el-table-column prop="usedQuantity" label="用料数量" width="">
                                    <template slot-scope="{ row, $index }">
                                        <el-input v-model.number="row.usedQuantity" size="small" @input="bomInputEvent($event,row,$index)" style="width:90%;" placeholder="请输入用料数量" :disabled="globalState"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="defectQuantity" label="不良数量" width="">
                                    <template slot-scope="{ row, $index }">
                                        <el-input v-model.number="row.defectQuantity" size="small" @input="bomInputEvent($event,row,$index)" style="width:90%;" placeholder="请输入不良数量" :disabled="globalState"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="statisticalQuantity" label="数据统计" width="">
                                    <template slot-scope="{ row, $index }">
                                        <el-input :value="row.statisticalQuantity" size="small" style="width:90%;" disabled placeholder="请输入"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>
</template>
  
<script>
import { reqUserInfo, reqProductOrderList, reqSaveData, reqLineList,reqProcessListByMaterialCode, reqProcessMaterialListByProcedureId,reqProcessMaterialList, reqOrderResidueCount,reqClassesList } from "@/api/workOrder.js";
import DowntReason from "@/components/downtReason/index.vue";
export default {
    name:"workorder1",
    props:['tempData','state'],
    components:{
        DowntReason
    },
    data(){
        var validate1 = (rule, value, callback) => {
            let unQualifiedNum = this.formData.unQualifiedNum;
            const planNumber = this.formData.planNumber;
            if (value === '') {
                callback(new Error('请输入完成数量'));
            } else if (parseInt(value < 0)) {
                callback(new Error('输入的数量非法'));
            } else if (parseInt(value) > parseInt(planNumber)) {
                callback(new Error('输入的完成数量不能大于计划数量'));
            } else if(parseInt(value) < parseInt(unQualifiedNum)){
                callback(new Error('完成数量不能小于不合格数量'));
            } else {
                callback();
            }
        };
        var validate2 = (rule, value, callback) => {
            let finishedNum =  this.formData.finishedNum;
            if (value === '') {
                callback(new Error('请输入不合格数量'));
            } else if (parseInt(value < 0)) {
                callback(new Error('输入的不合格数量非法'));
            } else if(finishedNum !== '' && parseInt(value) > parseInt(finishedNum)){
                callback(new Error('输入的不合格数量不能大于完成数量'));
            } else {
                callback();
            }
        };
        return {
            nickname:"",  //登录用户
            userId:"",  //用户id
            userPhone:"",
            lineList:[
                {lineName:"装配1线",materialCode:"61420045",materialName:"ELT09"},
                {lineName:"装配二线",materialCode:"61420049",materialName:"ELT13"},
                {lineName:"装配二线",materialCode:"61420106",materialName:"ELT23"},
                {lineName:"装配2线",materialCode:"614020-7",materialName:"ELT09安装盘"},
                {lineName:"装配2线",materialCode:"614104",materialName:"ELT09后盖"},
                {lineName:"装配3线",materialCode:"61420234",materialName:"ELT35"},
                {lineName:"装配3线",materialCode:"61420100",materialName:"ELT24"},
                {lineName:"装配4线",materialCode:"61420175",materialName:"BYD175"},
                {lineName:"装配4线",materialCode:"61420235",materialName:"丰沃925"},
                {lineName:"装配4线",materialCode:"9008013010",materialName:"508-9喷嘴环"},
                {lineName:"装配5线",materialCode:"61420230",materialName:"PSA2.2"},
                {lineName:"装配6线",materialCode:"61420216",materialName:"天力216"},
                {lineName:"装配6线",materialCode:"61420214",materialName:"天力TDE"},
                {lineName:"装配7线",materialCode:"61420181",materialName:"PSA1.2"}
            ],
            formData:{
                reportWay:"",
                lineName:'',
                lineNameList:[],
                materialName:"",  //品名/物料名称
                materialCode:"",
                materialList:[],  //品名下拉数组
                productOrder:"",  //订单号
                productOrderList:[],  //订单列表
                downtReasonList:[],
                classes:"",
                classesList:[],
                finishedNum:'',  //完成数量
                unQualifiedNum:'',  //不合格数量
                planNumber:"",  //计划数量
                qualifiedNum:"",  //合格数量
                equipmentRunningHours:"",
                attendanceHours:11,  //出勤工时 开始时间-结束时间
                incomingType:"",
                incomingTypeList:[]
            },
            formDataRules:{
                reportWay:[{required:true, message:"请选择报工方式", trigger: 'change'}],
                lineName:[{required:true, message:"请选择线体", trigger: 'change'}],
                materialCode:[{required:true, message:"请选择物料",trigger:"change"}],
                productOrder:[{required:true, message:"请选择订单号", trigger: 'change'}],
                classes:[{required:true, message:"请选择班次", trigger: 'change'}],
                finishedNum: [{required:true, validator: validate1, trigger: 'blur' }],
                unQualifiedNum:[{required:true, validator: validate2, trigger: 'blur' }],  //不合格数量
                equipmentRunningHours: [{required:true, validator:equipmentRunningHours, trigger: 'blur'}],
                attendanceHours: [{ required: true, message: '出勤工时不能为空', trigger: 'change'}]
            },
            //物料报废记录
            records:{
                date: this.formatDate(new Date(),1),
                recordTable:[],
                processMaterialTable:[]  //工序用料
            },
            lineNameFirstChange:true,
            materiaCodeFirstChange:true,
            productOrderFirstChange:true,
            reportWayFirstChange:true
        }
    },
    mounted(){
        this.getLineList();
        this.getClassList();
        console.log("获取到父组件传递过来的数据",this.tempData,this.state);
        if(this.tempData.workShopCode == 0){
            this.nickname = this.tempData.operator;
            this.userId = this.tempData.operatorId;
            this.userPhone = this.tempData.operatorPhone;
            this.formData.reportWay = this.tempData.workReportCode;
            this.formData.lineName = this.tempData.workReportType;
            this.formData.materialCode = this.tempData.productCode;
            this.formData.materialName = this.tempData.productName;
            this.formData.productOrder = this.tempData.productNumber;
            this.formData.finishedNum = this.tempData.completedQuantity;
            this.formData.unQualifiedNum = this.tempData.unqualifiedQuantity;
            this.formData.planNumber = this.tempData.plannedQuantity;
            this.formData.qualifiedNum = this.tempData.qualifiedQuantity;
            this.formData.attendanceHours = this.tempData.attendanceHours;
            this.formData.downtReason = this.tempData.downtimeReason;
            this.formData.downtHours = this.tempData.downtimeDuration;
            this.formData.downtReasonList = this.tempData.downtimeReportlList;
            this.formData.classes = this.tempData.classes;
            this.formData.equipmentRunningHours = this.tempData.equipmentRunningHours;
            this.records.date = this.formatDate(this.tempData.reportDate, 1);
            this.records.recordTable = this.tempData.productionProcessList.map(item => {
                return {defectQuantity:item.defectQuantity,processName:item.processName,id:item.id};
            });
            this.records.processMaterialTable = this.tempData.processMaterialList.map(item => {
                return {materialCode:item.materialCode,materialName:item.materialName,defectQuantity:item.quantity,id:item.id,usedQuantity:item.usedQuantity,statisticalQuantity:item.statisticalQuantity,remarks:""}
            });
        }
    },
    computed:{
        qualifiedNum(){
            let finishedNum = this.formData.finishedNum;
            let unQualifiedNum = this.formData.unQualifiedNum;
            if( finishedNum !== '' && unQualifiedNum !== '' && unQualifiedNum >= 0 && finishedNum >= unQualifiedNum){
                return finishedNum - unQualifiedNum;
            }
            return '';
        },
        //物料列表
        materialList(){
            let lineName = this.formData.lineName;
            return this.lineList.filter(item => item.lineName === lineName);
        },
        lineNameList(){
            let list = this.formData.lineNameList;
            const regex = /装配[234567二三四五六七]线/;
            return list.filter(k => regex.test(k));
        },
        globalState(){
            let state = this.state;
            if(state === 0 || state === 2){
                return true;
            }
            if(state === 1){
                return false;
            }
            return false;
        },
        downtReasonBtnInfo(){
            const downtReasonList = this.formData.downtReasonList;
            let tip = "点击填写";
            if(downtReasonList.length > 0){
                for(let i = 0; i < downtReasonList.length; i ++){
                    if(Number(downtReasonList[i].downtimeDuration) > 0){
                        tip = "点击修改";
                        return tip;
                    }
                }
                return tip;
            } else {
                return tip;
            }
        }
    },
    watch:{
        //监听物料选择的变化
        "formData.materialCode":{
            handler(newVal, oldVal){
                if(this.materiaCodeFirstChange){
                    this.materiaCodeFirstChange = false;
                    this.getProductOrderList();
                    return;
                }
                if(newVal !== oldVal && newVal !== ""){
                    //处理物料名称
                    let arr = this.materialList.filter(item => item.materialCode === newVal);
                    if(arr.length > 0){
                        this.formData.materialName = arr[0].materialName;
                    }
                    //获取对应物料的订单
                    this.formData.productOrder = "";
                    this.formData.productOrderList = [];
                    this.getProductOrderList();
                    if(this.formData.reportWay === 0){
                        //获取工序
                        this.records.recordTable = [];
                        this.getProcessListByMaterialCode();
                        //获取工序用料
                        this.records.processMaterialTable = [];
                        this.getAllProcessMaterialListInfo();
                    }
                }
                if(newVal === ""){
                    this.formData.productOrderList = [];
                    this.records.processMaterialTable = [];
                    this.records.recordTable = [];
                    this.formData.productOrder = "";
                    this.formData.planNumber = "";
                    console.log(this.records.recordTable);
                }
            }
        },
        //监听订单的选择
        "formData.productOrder":{
            handler(newVal, oldVal){
                if(this.productOrderFirstChange){
                    this.productOrderFirstChange = false;
                    return;
                }
                if(newVal !== oldVal && newVal !== ""){
                    //获取订单中的计划数量
                    let orderInfo = this.formData.productOrderList.filter(item => item.productOrderNumber === this.formData.productOrder)[0];
                    this.formData.planNumber = orderInfo.productOrderMaterial.planQuantity;
                }
                if(newVal === ""){
                    this.formData.planNumber = "";
                }
            }
        },
        //监听线体选择的变化
        "formData.lineName":{
            handler(newVal, oldVal){
                if(this.lineNameFirstChange){
                    this.lineNameFirstChange = false;
                    return;
                }
                if(newVal !== oldVal){
                    this.formData.materialCode = "";
                }
            },
        },
        "formData.reportWay":{
            handler(newVal,oldVal){
                if(this.reportWayFirstChange){
                    this.reportWayFirstChange = false;
                    return;
                }
                this.formData.lineName = "";
            }
        }
    },
    methods: {
        //获取当前用户信息
        async getUserInfo () {
            reqUserInfo().then(res => {
                if(res.data.code === 200){
                    this.nickname = res.data.data.nickname;
                    this.userId = res.data.data.id;
                    this.userPhone = res.data.data.mobile;
                }
                console.log("获取当前用户信息",res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        //查询线体信息
        async getLineList () {
            reqLineList().then(res => {
                if(res.data.code === 200){
                    let list = res.data.data.content.map(item => item.alias);
                    let arr = list.filter(item => {
                        return (item !== null && item !== "");
                    })
                    this.formData.lineNameList = Array.from(new Set(arr));
                }
                console.log('获取线体信息',res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        //选择物料后查询工序信息
        async getProcessListByMaterialCode(){
            let materialCode = this.formData.materialCode;
            reqProcessListByMaterialCode(materialCode).then(res => {
                if(res.data.code === 200 && res.data.data.length > 0){
                    //去掉目视工序
                    let list = res.data.data.filter(item => {
                        if(item.procedureName.includes("目视")){
                            return false;
                        }
                        return true;
                    })
                    this.records.recordTable = this.sortProcedures(list).map(item => {
                        return {procedureId:item.procedureId,processName:item.procedureName,supProcedureId:item.supProcedureId,nextProcedureId:item.nextProcedureId,defectQuantity:"",materialCodeList:[]};
                    });
                    //获取每个工序对应的用料信息
                    this.getProcessMaterialListByProcedureId();
                }
                console.log('根据物料号查询工序信息',res);
            }).catch(err => {
                this.$message({type:"error",message:"工序查询出错" + err});
            })
        },
        //根据工序id获取所有工序其对应工序用料
        getProcessMaterialListByProcedureId () {
            let materialCode = this.formData.materialCode;
            let list = this.records.recordTable;
            let temp = [];
            for (let i = 0; i < list.length; i++) {
                let procedureId = list[i].procedureId;
                temp.push(reqProcessMaterialListByProcedureId({procedureId,materialCode}));
            }
            Promise.all(temp).then(response => {
                for(let j = 0; j < response.length; j ++){
                    let materialCodeList = [];
                    if(response[j].data.data.length > 0){
                        for(let k = 0; k < response[j].data.data.length; k ++){
                            materialCodeList.push(response[j].data.data[k].materialCode);
                        }
                        this.records.recordTable.forEach(item => {
                            if(item.procedureId == response[j].data.data[0].procedureId){
                                item.materialCodeList = materialCodeList;
                            }
                        })
                    }
                }
                console.log('获取所有的产线工序对应的工序用料',response);
            }).catch(error => {
                this.$message({type:"error",message:"获取工序用料出错:"+error});
            })
        },
        //选择号物料后查询订单信息
        async getProductOrderList () {
            let materialCode = this.formData.materialCode;
            if(materialCode === "") return ;
            reqProductOrderList(materialCode).then(res => {
                if(res.data.code === 200){
                    this.formData.productOrderList = res.data.data.content;
                }
                console.log("通过物料编码/品名查询订单信息",res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        //工序不良数量输入事件
        processInputEvent(event,row,index){
            this.records.recordTable[index].defectQuantity = String(row.defectQuantity).replace(/[^\d]/g, '');
            console.log(event,row,index);
            //console.log(row.materialCodeList);
            if(!row.materialCodeList){
                /**
                 * 初始数据上没有关联的 materialCodeList 无法给其关联的赋值,
                 * 编辑时若触发了更换工序事件，则会请求到对应的数据，方可给其关联的值赋值
                 */
                return;
            }
            //修改引起工序用料的不良数量变化
            let materialCodeList = row.materialCodeList;
            let list = this.records.processMaterialTable;
            let array = this.records.recordTable;
            let temp = list.filter(item => {
                if(materialCodeList.includes(item.materialCode)){
                    return true;
                }
                return false;
            })
            //给其关联的设置值
            for(let j = 0; j < temp.length; j ++){
                //找出关联的工序用料对应的工序集合
                let sum = 0;
                for(let k = 0; k < array.length; k ++){
                    if(array[k].materialCodeList.includes(temp[j].materialCode)){
                        sum = (sum + Number(array[k].defectQuantity) * parseInt(temp[j].number));
                    }
                }
                temp[j].usedQuantity = sum;
                temp[j].statisticalQuantity = Number(temp[j].usedQuantity) + Number(temp[j].defectQuantity);
            }  
        },
        bomInputEvent(event,row,index) {
            this.records.processMaterialTable[index].defectQuantity = String(row.defectQuantity).replace(/[^\d]/g, '');
            //赋值
            row.statisticalQuantity = Number(row.usedQuantity) + Number(row.defectQuantity);
        },
        //保存/更新数据
        async save_btn(){
            //校验左右表单数据
            let validateResult1 = false;
            let validateResult2 = false;
            this.$refs.leftForm.validate((valid) => {
                if (valid) {
                    validateResult1 = true;
                } else {
                    validateResult1 = false;
                    return false;
                }
            });
            this.$refs.rightForm.validate((valid) => {
                if (valid) {
                    validateResult2 = true;
                } else {
                    validateResult2 = false;
                    return false;
                }
            });
            if(!(validateResult1 && validateResult2)) return ;
            //准备参数
            const { reportWay, lineName, materialName, materialCode, productOrder, downtReasonList, finishedNum, unQualifiedNum, planNumber, attendanceHours,classes, equipmentRunningHours } = this.formData;
            let processMaterialList = this.records.processMaterialTable.map(item => {
                return {materialCode:item.materialCode,materialName:item.materialName,quantity:item.defectQuantity,id:item.id,usedQuantity:item.usedQuantity,statisticalQuantity:item.statisticalQuantity,remarks:""};
            })
            //保存前判断报工前的完成数量是否合理
            const result = await reqOrderResidueCount({productNumber:productOrder,workReportCode:reportWay,plannedQuantity:planNumber});
            console.log('获取当前订单剩余计划数api',result);
            if(result.data || result.data.code === 200){
                const value = result.data.data;
                if(Number(finishedNum) > Number(value)){
                    this.$alert(`完成数量不能大于当前订单已报工完剩余的计划数量(${value})`,'提示',{confirmButtonText:"确定",callback:action => {}});
                    return;
                }
            } else {
                this.$message({type:"error",message:"请求订单剩余计划数量出错,请重试"});
                return ;
            }
            const paramsObj = {
               id:this.tempData.id,
               productName:materialName,
               productCode:materialCode,
               workReportCode:reportWay,
               workReportType:lineName,
               productNumber:productOrder,
               plannedQuantity:planNumber,
               completedQuantity:finishedNum,
               qualifiedQuantity: parseInt(finishedNum) - parseInt(unQualifiedNum),
               unqualifiedQuantity:unQualifiedNum,
               attendanceHours:attendanceHours,
               reportDate:this.records.date,
               operatorId:this.userId,
               operator:this.nickname,
               operatorPhone:this.userPhone,
               username:this.tempData.username,
               reviewStatus:0,
               classes:classes,
               classesTime:"",
               machine:"",
               machineCode:"",
               workShop:"装配线",
               workShopCode:0,
               appealStatus:0,
               appealRemark:"",
               inspectionPerson:"",
               inspectionPersonCode:"",
               productionProcessList:this.records.recordTable,
               processMaterialList:processMaterialList,
               warehouseCode:"",
               warehouseId:"",
               teamName:this.tempData.teamName,
               downtimeReportlList:downtReasonList,
               equipmentRunningHours:equipmentRunningHours
            }
            //判断是申诉状态下的编辑弹出提示
            if(this.tempData.appealStatus == 1){
                this.$confirm('该工单是申诉工单, 确认已修改其申诉内容后再进行保存!', '提示', { confirmButtonText: '确定', cancelButtonText: '取消',type: 'warning'})
                .then(() => {
                    reqSaveData(paramsObj).then(res => {
                        console.log("保存数据api",res);
                        if(res.data.code === 200){
                            this.$emit("message",true);
                            return;
                        }
                        this.$emit("message",false);
                    }).catch(err => {
                        this.$emit("message",false);
                    })
                }).catch(() => {
                    this.$message({type: 'info',message: '已取消!'});       
                });
                return;
            }
            reqSaveData(paramsObj).then(res => {
                console.log("保存数据api",res);
                if(res.data.code === 200){
                    this.$emit("message",true);
                    return;
                }
                this.$emit("message",false);
            }).catch(err => {
                this.$emit("message",false);
            })
        },
        //格式化时间
        formatDate(val,type){
            let date = new Date(val);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();
            if(type === 0){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 1){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day);
            } else if (type === 2){
                return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 3){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
            }
        },
        addZero(val){
            return val > 9 ? val : "0" + val;
        },
        //根据物料编码获取其所有工序的所有用料信息
        getAllProcessMaterialListInfo(){
            let materialCode = this.formData.materialCode;
            reqProcessMaterialList(materialCode).then(res => {
                if(res.data.code === 200 && res.data.data.length > 0){
                    let list = res.data.data;
                    const seen = new Set();
                    this.records.processMaterialTable = list.filter((ele,index,self) => {
                        if(!seen.has(ele.materialName)){
                            seen.add(ele.materialName);
                            ele.usedQuantity = 0;
                            ele.defectQuantity = 0;
                            ele.statisticalQuantity = 0;
                            return true;
                        }
                        return false;
                    })
                }
                console.log('通过物料编码查询工序用料信息',res);
            }).catch(err => {
                this.$message({type:"error",message:"查询工序用料信息出错"+err});
            })
        },
        //对工序进行排序(工具函数)
        sortProcedures(originProceduresList) {
            let sortedProcedures = [];
            const procedureMap = new Map();
            //找出所有的初始工序
            let initProcessList = originProceduresList.filter(item => (item.supProcedureId === "" || item.supProcedureId === null));
            let proceduresList = originProceduresList.filter(item => (item.supProcedureId !== "" && item.supProcedureId !== null));
            // 将工序信息存入Map中，方便后续查找
            proceduresList.forEach(procedure => {
                procedureMap.set(procedure.id, procedure);
            });
            let list = [];
            for(let i = 0; i < initProcessList.length; i ++){
                let temp = [];
                // 找到没有上一道工序的工序作为起始点
                let startProcedure = initProcessList[i];
                while (startProcedure) {
                    temp.push(startProcedure);
                    const nextProcedure = procedureMap.get(startProcedure.nextProcedureId);
                    if (nextProcedure) {
                        startProcedure = nextProcedure;
                    } else {
                        break;
                    }
                }
                initProcessList[i].procedureList = temp;
                list.push(initProcessList[i]);
            }
            let id = "";
            for(let j = 0; j < list.length; j ++){
                if(list[j].procedureList.length > sortedProcedures.length){
                    id = list[j].id;
                    sortedProcedures = list[j].procedureList;
                }
            }
            //插入另一分支的头节点
            if(list.length > 1){
                let temp = [];
                let headProcess = list.filter(item => item.id != id)[0];
                for(let k = 0; k < sortedProcedures.length; k ++){
                    if(sortedProcedures[k].id == headProcess.nextProcedureId){
                        temp.push(headProcess);
                    }
                    temp.push(sortedProcedures[k]);
                }
                sortedProcedures = temp;
            }
            console.log("去除目视后的工序进行排序:",sortedProcedures);
            return sortedProcedures;
        },
        wirteDowntReason(){
            this.$refs.downtReason.dialogFormVisible = true;
        },
        downtReasonClose(parameter){
            this.formData.downtReasonList = parameter;
        },
        async getClassList() {
            reqClassesList().then(res => {
                if(res.data.code === 200){
                    this.formData.classesList = res.data.data;
                }
                console.log('获取班次信息',res);
            }).catch(err => {
                this.$message({type:"error",message:"网络异常，班次信息获取失败"});
            })
        }
    }
}
</script>
  
<style lang="scss" scoped>
.workorder{
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    user-select: none;
    .page-main{
        width: 100%;
        flex:5;
        display: flex;
        justify-content: space-around;
        .main-left{
            width: 45%;
            box-sizing: border-box;
        }
        .main-right{
            width: 45%;
            box-sizing: border-box;
        }
    }
    .page-records{
        width: 95%;
        flex: 3;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        .records-head{
            display: flex;
            flex-direction: column;
            .head-title{
                font-size: 17px;
                font-weight: 500;
            }
            .head-main{
                display: flex;
                justify-content: space-between;
                margin: 1% 0;
                .main-item{
                    display: flex;
                    align-items: center;
                    .item-tip{
                        font-size: 14px;
                        margin-right: 15px;
                    }
                }
            }
        }
        .records-process{
            display: flex;
            flex-direction: column;
            margin: 5px 0;
            .process-content{
                display: flex;
                flex-direction: column;
                margin: 5px 0;
                .process-table{
                    width: 100%;
                    overflow: auto;
                    margin: 5px 0;
                }
                .bom-table{
                    width: 100%;
                    overflow: auto;
                }
            }
        }
    }
}
//el-time-picker组件响应式变化
.time-picker {
  width: 80%; /* 在小屏幕上设置为100%宽度 */
}
</style>
  